package jprint.jfx;

import java.io.File;
import java.util.Optional;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import jprint.base.AppContext;

/**
 * @author zw-zheng
 * Created on 2021-02-06
 */
public class UpdateAlert {

    private Alert alert;

    public void show() {
        Platform.runLater(() -> {
            alert = new Alert(Alert.AlertType.CONFIRMATION,
                              "",
                              ButtonType.YES,
                              ButtonType.NO);
            alert.setTitle("检查更新");
            alert.setHeaderText("检查新版本时，需要先退出本程序，是否继续？");
            Optional<ButtonType> buttonType = alert.showAndWait();
            if (buttonType.get() == ButtonType.YES) {
                alert.close();
                AppContext appContext = AppContextImpl.getInstance();
                File exeFile = new File(appContext.getAppHome(), "lblprn.exe");
                if (exeFile.exists() && exeFile.isFile()) {
                    checkUpdate(exeFile);
                } else {
                    alert.setAlertType(Alert.AlertType.INFORMATION);
                    alert.setHeaderText("可执行文件：" + exeFile.getAbsolutePath() + " 无效，检查更新失败！");
                    alert.getButtonTypes().removeAll(ButtonType.YES, ButtonType.NO);
                    alert.getButtonTypes().add(ButtonType.OK);
                    alert.getDialogPane().setPrefWidth(360);
                    alert.show();
                }
            } else {
                alert.close();
            }
        });
    }

    private void checkUpdate(final File exeFile) {
        AppContext appContext = AppContextImpl.getInstance();
        appContext.exit();
        Platform.exit();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                Thread.sleep(500);
                Runtime.getRuntime().exec(new String[] { exeFile.getAbsolutePath(), "-u" });
            } catch (Exception ignored) {
                // ignored
            }
        }, "start_update"));
        System.exit(0);
    }
}
